package xyz.chaobei.gateway2.inbound;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.chaobei.gateway2.filter.HeaderRequestFilter;
import xyz.chaobei.gateway2.filter.HttpRequestFilter;
import xyz.chaobei.gateway2.outbound.client4.HttpOutBounderHandler;

@Slf4j
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {

    private String proxy;
    private HttpOutBounderHandler outBounderHandler;
    private HttpRequestFilter requestFilter;

    public HttpInboundHandler(String proxy) {
        this.proxy = proxy;
        this.outBounderHandler = new HttpOutBounderHandler(proxy);
        this.requestFilter = new HeaderRequestFilter();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        FullHttpRequest request = (FullHttpRequest) msg;

        // 执行过滤器
        requestFilter.doFilter(request,ctx);

        outBounderHandler.handle(request, ctx);

        ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
